package com.anxin.service.impl;

import com.anxin.entity.Department;
import com.anxin.mapper.DepartmentMapper;
import com.anxin.service.DepartmentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Override
    public List<Department> getDepartmentTree() {
        // 获取所有科室
        List<Department> allDepartments = this.list();
        
        // 构建树形结构
        Map<String, List<Department>> parentMap = allDepartments.stream()
                .collect(Collectors.groupingBy(Department::getParentId));
        
        // 获取根节点
        return parentMap.getOrDefault(null, new ArrayList<>());
    }

    @Override
    public List<Department> getChildrenDepartments(String parentId) {
        return this.list(new LambdaQueryWrapper<Department>()
                .eq(Department::getParentId, parentId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDepartmentStatus(String departmentId, Integer status) {
        Department department = new Department();
        department.setId(departmentId);
        department.setStatus(status);
        this.updateById(department);
    }
}
